<template>
  <div id="search">
    <van-nav-bar title="搜索" left-text="返回" left-arrow @click-left="$router.go(-1)" />

    <div class="top_search_box">
      <input class="search_input" v-model="keywords" placeholder="搜索商品名称/编号" />
      <button class="search_button" @click="toSearch(keywords)">搜索</button>
    </div>

    <section class="history" v-show="historyShow">
      <van-cell title="历史搜索">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <van-icon slot="right-icon" name="delete" style="line-height: inherit;" @click="clearSearchHistory" />
      </van-cell>

      <ul class="history_keywords">
        <li v-for="item in historySearch" @click="toSearch(item)">{{ item }}</li>
      </ul>
    </section>

    <section class="result">
      <ul class="common">
        <li @click="toOrderSearch()" :class="common_active()">默认</li>
        <li @click="toOrderSearch('id')" :class="common_active('id')">新品</li>
        <li v-if="order_price" @click="toOrderSearch('price')" :class="common_active('price')">价格↑</li>
        <li v-else @click="toOrderSearch('price')" :class="common_active('price')">价格↓</li>
        <li @click="toOrderSearch('sale_count')" :class="common_active('sale_count')">销量</li>
      </ul>

      <van-list v-model="loading" :finished="finished" :immediate-check="false" :finished-text="finished_text" @load="loadMore">
        <ul class="goods_lists van-clearfix">
          <li v-for="item in lists">
            <div class="goods" @click="goToDetailsPage(item.id)">
              <div class="image"><img :src="item.image" /></div>
              <div class="title">{{ item.title }}</div>
              <div class="price">
                ￥
                <span>{{ item.price }}</span>
              </div>
            </div>
          </li>
        </ul>
      </van-list>
      <is-empty v-if="isEmpty">抱歉,没有搜到任何商品</is-empty>
    </section>
  </div>
</template>

<script>
import loadMore from '@/components/mixin/load-more';
import IsEmpty from '@/components/include/empty';
export default {
  mixins: [loadMore],
  components: {
    [IsEmpty.name]: IsEmpty
  },
  data() {
    return {
      historyShow: true,
      keywords: '',
      order: '',
      order_price: 1,
      lists: [],
      finished_text: '没有更多了',
      historySearch: [] //存放历史搜索的关键词
    };
  },
  computed: {
    common_active() {
      return function(val = '') {
        // if (this.order.indexOf(val) != -1) {
        //   return 'active';
        // }
      };
    }
  },
  mounted() {
    console.log('mounted');

    // this.keywords = this.$route.query.keywords;

    //   this.lists = [];
    //   this.resetInit();
    //   this.loadMore();
  },
  created() {
    this.historyShow = true;

    //this.loadLists();
    // this.onLoad()

    // 加载历史搜索
    let searchHistory = localStorage.getItem('searchWord');
    if (searchHistory) {
      this.historySearch = searchHistory.split(',');
      console.log(this.historySearch);
    }
  },
  methods: {
    goToDetailsPage(id) {
      this.$router.push({
        path: '/goodsViews',
        query: {
          goods_id: id
        }
      });
    },

    //储存历史搜索
    saveSearchHistory() {
      let searchWord = localStorage.getItem('searchWord');
      if (searchWord == null) {
        if (this.keywords !== '' && typeof this.keywords != 'undefined') localStorage.setItem('searchWord', this.keywords);
      } else {
        let arr = localStorage.getItem('searchWord');
        arr = arr.split(',');
        //去除重复的历史搜索
        if (arr.indexOf(this.keywords) != -1) {
          arr = arr;
        } else {
          // unshift() 方法可向数组的开头添加一个或更多元素，并返回新的长度。
          if (this.keywords !== '' && typeof this.keywords != 'undefined') arr.unshift(this.keywords);
        }
        this.historySearch = arr;
        //设置历史搜索最多显示多少条
        if (this.historySearch.length > 10) {
          // pop() 方法用于删除并返回数组的最后一个元素。
          this.historySearch.pop();
        }
        localStorage.setItem('searchWord', this.historySearch);
      }
    },
    //清除搜索历史
    clearSearchHistory() {
      this.historySearch = [];
      localStorage.removeItem('searchWord');
    },

    async loadMore() {
      //console.log('onload');

      this.apiPost('/shop.goods/search', {
        page_size: this.pages.pageSize,
        page: this.pages.currPage,
        keywords: this.keywords,
        order: this.order
      }).then(res => {
        //  this.pages.listsCount = res.data.length;
        // console.log('res.data.length' + res.data.length);

        // 存储搜索关键字
        this.saveSearchHistory();

        if (res.data.length == 0 && this.pages.currPage == 1) {
          this.finished_text = '';
          this.finished = true;
          this.isEmpty = true;
          this.historyShow = false;
          return false;
        } else {
          this.finished_text = '没有更多了';
        }

        this.lists.push(...(res.data || []));

        if (res.data.length < this.pages.pageSize) {
          this.isFinished();
        } else {
          this.nextPage();
        }

        this.historyShow = false;
      });
    },

    toOrderSearch(value) {
      this.order = value;

      if (value == 'price') {
        this.order_price = !this.order_price;
        this.order = this.order_price ? 'price_asc' : 'price_desc';
      }

      this.toSearch(this.keywords);
    },
    toSearch(value) {
      if (value != '') {
        this.keywords = value;
      }

      // this.$router.replace({
      //   path: "search",
      //   query: {
      //     keywords: value
      //   }
      // });

      // this.$router.go(0)

      //请求后台
      this.lists = [];
      this.resetInit();
      this.loadMore();
    }
  }
};
</script>

<style lang="scss">
  @import "@/assets/scss/variable.scss";
.goods_lists {
  padding: 1px;

  overflow: hidden;
  li {
    display: block;
    float: left;
    width: 50%;
    box-sizing: border-box;
    .goods {
      background-color: white;
      margin: 2px;
      img {
        width: 100%;
      }
      .title {
        font-size: 14px;
        padding: 5px;
      }
      .price {
        padding: 5px;
        font-weight: bold;
        color: $colorAccent;
        span {
          font-size: 18px;
        }
      }
    }
  }
}

.top_search_box {
  margin-bottom: 2px;
}

.common {
  background-color: white;
  display: table;
  width: 100%;
  li {
    display: table-cell;
    text-align: center;
    font-size: 13px;
    padding-top: 10px;
    padding-bottom: 10px;
    border-right: 1px solid #efefef;
    .active {
      font-weight: bold;
    }
  }
  &:last-child {
    border-right: 0;
  }
  border-bottom: 2px solid #efefef;
}

.result {
  height: 100%;
}

.history_keywords {
  overflow: hidden;
  li {
    float: left;
    font-size: 12px;
    background-color: #efefef;
    margin-top: 10px;
    margin-left: 10px;
    padding: 5px 8px;
  }
}

#search {
  height: 100%;
}
.history {
  height: 100%;
  background-color: white;
}

.moveR-enter-active,
.moveR-leave-active {
  transition: all 0.3s linear;
  transform: translateX(0);
}
.moveR-enter,
.moveR-leave {
  transform: translateX(100%);
}
.moveR-leave-to {
  transform: translateX(100%);
}
</style>
